<template>
  <div>
    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="success" @click="handleAddType">新增类型</el-button>
    </div>

    <!-- 类型表格 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="typeId" label="类型ID" width="80"/>
      <el-table-column prop="typeName" label="类型名称"/>
      <el-table-column prop="createdTime" label="创建时间"/>
      <el-table-column prop="updatedTime" label="更新时间"/>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditType(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteType(scope.row.typeId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑类型对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40%">
      <el-form :model="currentForm" :rules="rules" ref="typeFormRef">
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="currentForm.typeName" placeholder="请输入类型名称"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {
  videoTypeDeleteOne,
  videoTypeInsertOne,
  videoTypeSelectPage,
  videoTypeUpdateOne
} from "@/api/material.js";

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const currentForm = reactive({
  typeId: null,
  typeName: '',
});
const typeFormRef = ref(null);

// 验证规则
const rules = {
  typeName: [
    {required: true, message: '类型名称不能为空', trigger: 'blur'},
    {min: 2, max: 20, message: '类型名称长度在2到20个字符之间', trigger: 'blur'}
  ],
};

// 获取类型列表
const fetchTypes = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    };
    const response = await videoTypeSelectPage(params);
    tableData.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    ElMessage.error('获取类型列表失败');
  }
};

// 新增类型
const handleAddType = () => {
  dialogTitle.value = '新增类型';
  dialogVisible.value = true;
  resetForm();
};

// 编辑类型
const handleEditType = (row) => {
  dialogTitle.value = '编辑类型';
  dialogVisible.value = true;
  Object.assign(currentForm, row);
};

// 删除类型
const handleDeleteType = (typeId) => {
  ElMessageBox.confirm('确认删除该类型?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await videoTypeDeleteOne(typeId);
      ElMessage.success('删除成功');
      await fetchTypes();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

// 保存类型（新增/编辑）
const handleSubmit = () => {
  typeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (currentForm.typeId) {
          // 编辑
          await videoTypeUpdateOne(currentForm);
        } else {
          // 新增
          await videoTypeInsertOne(currentForm)
        }
        ElMessage.success('保存成功');
        dialogVisible.value = false;
        await fetchTypes();
      } catch (error) {
        ElMessage.error('保存失败');
      }
    }
  });
};

// 分页事件
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchTypes();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchTypes();
};

// 重置表单
const resetForm = () => {
  Object.assign(currentForm, {
    typeId: null,
    typeName: '',
  });
  typeFormRef.value?.clearValidate();
};

// 初始化数据
onMounted(() => {
  fetchTypes();
});
</script>

<style scoped>
.action-bar {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
